import './todolist.css'
import { useSelector, useDispatch } from 'react-redux'
import { add } from '../../store/modules/todoListStore.js'
import React from 'react';
import { del, toggle,toggleAll,getcompleted } from '../../store/modules/todoListStore.js';

function App() {

  //引入仓库的list
  const { list } = useSelector(state => state.todoList)
  //引用addInput
  const dispatch = useDispatch()
  //获取input的值,然后调用add方法
  
  const addInput = (e) => {
    if (e.key === 'Enter') {
      dispatch(add(e.target.value))
      console.log(e.target.value)
      e.target.value = ''
    }
  }
  //删除数据
  const delInput = (e) => {
    if (e.key === 'Delete') {
      dispatch(del(e.target.value))
      console.log(e.target.value)
      e.target.value = ''
    }
  }
  const isAllChecked = () => {
    dispatch(getcompleted())
  }
  // 切换完成状态
  const toggleCompleted = (index) => {
    dispatch(toggle(index))
  }
  //全选
  const getAll = (e) => {
    dispatch(toggleAll(e.target.checked))
  }
  //引入allChecked
  const {allChecked} = useSelector(state => state.todoList)

  return (
    <section className="todoapp">
      <header className="header">
        <h1>todos</h1>
        <input
          onKeyDown={addInput}
          key={list.length}
          className="new-todo"
          autoFocus
          autoComplete="off"
          placeholder="What needs to be done?"
        />
      </header>
      <section className="main">
        
        <input id="toggle-all" className="toggle-all" type="checkbox" key={list.length} onChange={getAll} checked={allChecked}  />
        <label htmlFor="toggle-all"></label>
        <ul className="todo-list">
          {
            list.map((item, index) => {
              return <li key={item.id} className={item.completed ?'':'completed'}>
                <div className="view">
                  <input
                    className="toggle"
                    type="checkbox"
                    checked={item.completed}
                    onChange={() => toggleCompleted(index)}
                    
                  />
                  <label>{item.name}</label>
                  <button className="destroy" onClick={() => {
                    dispatch(del(index))
                  }}></button>
                </div>
              </li>
            })
          }
        </ul>
      </section>
    </section>
  )
}

export default App